﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    public class HtmlAnalyzer
    {
        public static List<Company> Parse(string html)
        {
            List<Company> list = new List<Company>();

            Regex reg = new Regex("<div class=\"link_normal\">[\\w\\W]*?<div class=\"xdir_intro_footer\">");
            foreach (Match m in reg.Matches(html))
            {
                try
                {
                    string name, address;
                    string item = m.Value;
                    int nameStart = item.IndexOf(">", item.IndexOf("<a", item.IndexOf("<div class =\"xdir_title\">")));
                    if (nameStart == -1)
                        continue;
                    int nameEnd = item.IndexOf("<img") >= 0 ? item.IndexOf("&nbsp;", nameStart) : item.IndexOf("</a>", nameStart);
                    if (nameEnd == -1)
                        continue;
                    name = item.Substring(nameStart + 1, nameEnd - nameStart - 1);

                    int addressStart = item.IndexOf("地址：");
                    if (addressStart == -1)
                        continue;
                    int addressEnd = item.IndexOf("<br/>", addressStart);
                    if (addressEnd == -1)
                        continue;
                    address = item.Substring(addressStart + 3, addressEnd - addressStart - 3);

                    list.Add(new Company { Name = name, Address = address });
                }
                catch (Exception e)
                {
                    throw e;
                    continue;
                }
            }

            return list;
        }
    }
}
